if the function keyword is the first in the statement, then it's a function declaration. Otherwise it's a function expression. (Kyle Simpson)
// 1\. function declaration
function foo(){}
foo(); // no error
// 2\. function expression
var foo = function bar(){
var baz = bar; // it's ok. bar is enclosed in its own scope
}
bar(); // Error
// 3\. anonymous function expression
// hint : we cannot reference it for recursion, because no name.
var anotherfoo = function(){}
comes from the lexing phase of the compiler => it's a compile time scope. explained here
the eval() keyword cheats the lexical scope. it can add variable to the scope at runtime
function foo(str){
eval(str);
console.log(bar); // this prints 42, even though bar is not in the lexical scope
}
foo("var bar = 42;");
eval() made the compiler skip all optimization.
(function(){})();
(function(){}());
we can pass parameters to an IIFE
var myVal= 42;
(function(configVal){
console.log(configVal); // prints 42
})(myVal);
var foo = "foo";
function bar(str){
for(var i = 0; i < 10; i++){}
console.log(i); // prints 10
for(let j = 0; j < 10; j++){}
console.log(j); // ERROR !
}
bar(foo);